<?php

namespace app\controller\system;

use app\BaseController;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class Account extends BaseController
{
    public function login(): Json
    {
        return $this->handle(function () {
            $param = $this->request->post();
            $account = \app\model\Account::where('account', $param['account'])->where('state', 1)->where('is_del', 1)->find();
            if (empty($account)) throw new \Exception('账号不存在', 7001);
            if (!checkPassword($param['password'], $account['password'], $account['code'])) throw new \Exception('密码错误', 7002);
            $last_time = strtotime("24 hours");
            $token = Str::random(12, 6);
            $data = [
                "token" => $token,
                "account_id" => $account['id'],
                "expire_time" => $last_time
            ];
            Cache::set($token, $data, $last_time);
            return $data;
        });
    }

    public function query(): Json
    {
        return $this->handle(function () {
            return $this->request->account;
        });
    }

    public function detail(): Json
    {
        return $this->handle(function () {
            return $this->app->make(\app\model\Account::class)->where('id', $this->request->param("id"))->find();
        });
    }

    public function lst(): Json
    {
        return $this->handle(function () {
            return $this->app->make(\app\model\Account::class)->pageData();
        });
    }

    public function save(): Json
    {
        return $this->handle(function () {
            return $this->app->make(\app\model\Account::class)->insertData();
        });
    }

    public function delete(): Json
    {
        return $this->handle(function () {
            $param = request()->param();
            $this->app->make(\app\model\Account::class)->where('id', $param['id'])->update(['is_del' => 0]);
            return ['errMsg' => '删除成功！'];
        });
    }

    public function search(): Json
    {
        return $this->handle(function () {
            return $this->app->make(\app\model\Account::class)->where('state', 1)->where('is_del', 1)->where('type', 1)->column("id,name");
        });
    }

    public function modify(): Json
    {
        return $this->handle(function () {
            $user = $this->request->account;
            $param = $this->request->post();
            if (!checkPassword($param['oldPassword'], $user['password'], $user['code'])) throw new \Exception("旧密码错误！");
            $password = setPassword($param['newPassword']);
            $user->save([
                "password" => $password['password'],
                "code" => $password['token']
            ]);
            return $user;
        });
    }
}
